package ferp.center.server.backend;

import ferp.center.server.Action;
import ferp.center.server.entity.Bid;
import ferp.center.server.entity.Config;
import ferp.center.server.servlet.ConfigGet;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * User: olegs
 * Date: 11/21/12 4:44 PM
 */
public class BidDelete extends HttpServlet
{
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    // create inactive profile deletion task
    Action.queueTaskForBackend(response, "delete old bids", "/bid/delete");
  }

  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, Void.class, new Action.Read<Void, Void>()
    {
      public Void run(EntityManager em, Void input) throws IOException
      {
        Config c = ConfigGet.current(em);
        int tss = 0;

        if (c != null && (tss = c.getTrainingSetSize()) > MAX_TRAINING_SET_SIZE)
        {
          Query q = em.createQuery("SELECT b FROM Bid b ORDER BY b.created");

          log("current configuration id: " + c.getId() + ", tss: " + tss);

          //q.setParameter(1, new Date(System.currentTimeMillis() - MAX_DAYS_IN_MS));
          q.setMaxResults(Math.min(CHUNK_SIZE, (tss - MAX_TRAINING_SET_SIZE) / 24));

          List<Bid> bids = q.getResultList();

          for (Bid b : bids)
            em.remove(b);

          log("old bids deleted: " + bids.size());
        }
        else
          log("training set size is too small: " + tss);

        return null;
      }
    });
  }

  // 10 days old bids
  private static final int MAX_DAYS = 10;

  //private static final long MAX_DAYS_IN_MS = MAX_DAYS * 24 * 60 * 60 * 1000;
  private static final int CHUNK_SIZE = 5000;
  private static final int MAX_TRAINING_SET_SIZE = 300000;
}
